<?php
namespace app\api\controller;
use app\common\controller\CommonApi;
use Pay\Pay;

/**
 * 红包模块
 */
class Red extends CommonApi{
    protected $tn = 'common/red_packet';


    /**
     * [发红包]
     * @return [type] [description]
     */
    public function issue(){
        $validate = validate($this->tn);
        if($validate->check($this->post) === false){
            $this->apiReturn(0,$validate->getError());
        }

        if(intval($this->post['num']) < 10){
            $this->apiReturn(0,'红包数量至少为10个');
        }
        if(floatval($this->post['price']) < 1){
            $this->apiReturn(0,'红包金额最少为1元');
        }
        //红包人均不得小于1分
        if(floatval($this->post['price'])/intval($this->post['num']) < 0.01){
            $this->apiReturn(0,'人均红包不得小于1分');
        }


        if($this->post['jump'] != 3){
            if(!isset($this->post['foreign_key']) || intval($this->post['foreign_key']) <= 0){
                $this->apiReturn(0,'请选择跳转项');
            }
            if($this->post['jump'] == 1){
                $model = model('comment/service');
            }else{
                $model = model('comment/need');
            }

            $info = $model->where('id',intval($this->post['foreign_key']))->where('user_id',UID)->where('status',1)->find();
            if(is_null($info)){
                $this->apiReturn(0,'跳转项不存在');
            }
        }
        
        //第一次发红包必须为现金红包
        $issue_num = db('red_packet')->where('user_id',UID)->where('pay_status','neq',0)->count();

       /* if($issue_num <= 0 && intval($this->post['pay_type']) == 0){
            $this->apiReturn(0,'第一次必须为现金红包');
        }   */

        $this->post['user_id'] = UID;
        $this->post['order_no'] = date('YmdHis').rand(10000,99999);
        $this->post['get_num'] = intval($this->post['num']);
        $this->post['odd_price'] = floatval($this->post['price']);
        //余额支付
        if(intval($this->post['pay_type']) == 0){
            if($this->user_info['balance'] < floatval($this->post['price'])){
                $this->apiReturn(0,'账户余额不足');
            }
           
            $this->post['pay_status'] = 1;
            $this->post['pay_time'] = time();
            db()->startTrans();
            if(!model($this->tn)->allowField(true)->save($this->post)){
                db()->rollback();
                $this->apiReturn(0,'下单失败');
            }

            if(!db('user')->where('id',UID)->setDec('balance',floatval($this->post['price']))){
                db()->rollback();
                $this->apiReturn(0,'扣除余额失败');
            }

            if(!db('bill')->insert([
                    'user_id' => UID,
                    'type' => 1,
                    'num' => floatval($this->post['price']),
                    'foreign_key' => model($this->tn)->id,
                    'add_time' => time()
                ])){
                db()->rollback();
                $this->apiReturn(0,'交易明细添加失败');
            }

            if(!db('information')->insert([
                    'user_id' => UID,
                    'type' => 1,
                    'content' => '支付成功',
                    'add_time' => time()
                ])){
                db()->rollback();
                $this->apiReturn(0,'添加信息失败');
            }
            db()->commit();
            $this->apiReturn(1,'发布成功');
        }

        //微信支付
        if(intval($this->post['pay_type']) == 1){
            if(!model($this->tn)->allowField(true)->save($this->post)){
                db()->rollback();
                $this->apiReturn(0,'下单失败');
            }
            $options = [
                'out_trade_no' => $this->post['order_no'],
                'total_fee' => floatval($this->post['price'])*100,
                'body' => '发红包',
                'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
                'attach' => serialize(['attach' => 1])
            ];

            $pay = new Pay(config('pay'));

            try{
                $result = $pay->driver('wechat')->gateway('app')->apply($options);
                $this->apiReturn(1,'微信支付信息',$result);
            } catch (Exception $e){
                $this->apiReturn(0,$e->getMessage());

            }
        }
        
        //支付宝支付
        if(intval($this->post['pay_type']) == 2){
            if(!model($this->tn)->allowField(true)->save($this->post)){
                db()->rollback();
                $this->apiReturn(0,'下单失败');
            }

            $options = [
                'out_trade_no' => $this->post['order_no'],
                'total_amount' => floatval($this->post['price']),
                'subject' => '发红包',
                'passback_params' => UrlEncode(serialize(['passback_params' => 1]))
            ];
            $pay = new Pay(config('pay'));
            try{
                $result = $pay->driver('alipay')->gateway('app')->apply($options);
                $this->apiReturn(1,'支付宝支付信息',$result);
            } catch (Exception $e){
                $this->apiReturn(0,$e->getMessage());

            }
        }
    }


    /**
     * [getRed 领取红包]
     * @return [type] [description]
     */
    public function getRed(){
        if(!isset($this->post['id']) || intval($this->post['id']) <= 0){
            $this->apiReturn(0,'参数id丢失');
        }
        $model = model($this->tn)->get(intval($this->post['id']));
        if(is_null($model)){
            $this->apiReturn(0,'红包不存在或已被删除');
        }

        if($model['odd_price'] <= 0 || $model['get_num'] <= 0){
            $this->apiReturn(0,'红包已经领完');
        }
        
        if($model['pay_status'] != 1){
            $this->apiReturn(0,'该红包已经过期');
        }

        if(db('red_packet_get')->where('foreign_key',intval($this->post['id']))->where('get_user_id',UID)->find()){
            $this->apiReturn(0,'只能领取一次');
        }

        $get_price = model($this->tn)->getPrice($model['odd_price'],$model['get_num']);
        db()->startTrans();
        if(!$model->save([
            'odd_price' => ['dec',floatval($get_price)],
            'get_num' => ['dec',1]
        ])){
            db()->rollback();
            $this->apiReturn(0,'修改信息失败，请稍后再试');
        }
        //添加红包记录
        if(!db('red_packet_get')->insert(
            [
                'foreign_key' => intval($this->post['id']),
                'get_user_id' => UID,
                'price' => floatval($get_price),
                'add_time' => time()
            ])){
            db()->rollback();
            $this->apiReturn(0,'红包记录添加失败');
        }
        //添加资金记录
        if(!db('bill')->insert([
            'user_id' => UID,
            'type' => 2,
            'num' => floatval($get_price),
            'foreign_key' => intval($this->post['id']),
            'add_time' => time()
        ])){
            db()->rollback();
            $this->apiReturn(0,'资金记录添加失败');
        }

        //添加消息通知
        if(!db('information')->insert([
            'user_id' => UID,
            'type' => 2,
            'content' => '领取红包'.floatval($get_price).'元',
            'add_time' => time()
        ])){
            db()->rollback();
            $this->apiReturn(0,'消息通知添加失败');
        }
        //修改账户余额
        if(!db('user')->where('id',UID)->setInc('balance',floatval($get_price))){
            db()->rollback();
            $this->apiReturn(0,'账户余额修改失败');
        }
        db()->commit();
        $jump = $model['jump'] == 3 ? $model['foreign_key'] : $model['user_id'];
        $this->apiReturn(1,'领取成功',[
            'jump_type' => $model['jump'],
            'jump' => $jump,
            'price' => floatval($get_price),
        ]);
    }

    //红包统计
    public function myRedSum(){
        if(!isset($this->post['type']) || !in_array($this->post['type'],[1,2])){
            $this->apiReturn(0,'参数type错误');
        }
        $where['add_time'] = [['egt',strtotime(date('Y-m-d'))],['lt',strtotime(date('Y-m-d').'+1 day')]];
        //发布红包
        if($this->post['type'] == 1){
            //总共发布红包金额
            $sum = db('red_packet')->where('user_id',UID)->sum('price');
            $today = db('red_packet')->where('user_id',UID)->where($where)->sum('price');
        }else{
            $sum = db('red_packet_get')->where('get_user_id',UID)->sum('price');
            $today = db('red_packet_get')->where('get_user_id',UID)->where($where)->sum('price');
        }
        $this->apiReturn(1,'',[
            'sum' => $sum,
            'today' => $today
        ]);
    }

    //我的红包记录 1:我发布的红包   2：我抢到的红包
    public function myRed(){

        if(!isset($this->post['type']) || !in_array($this->post['type'],[1,2])){
            $this->apiReturn(0,'参数type错误');
        }
        
        if($this->post['type'] == 1){
        
            //一个月内的数据
            $result = db('red_packet')->field('FROM_UNIXTIME(add_time,"%Y-%m") as format_time')->where('user_id',UID)->where('pay_status','neq',0)->group('format_time')->order('add_time desc')->limit(($this->p-1)*1,1)->select();

            if(empty($result)){
                $this->apiReturn(1,'',[]);
            }
            $list = model('common/red_packet')->redList("FROM_UNIXTIME(r.add_time,'%Y-%m') = '".$result[0]['format_time']."' and r.user_id = ".UID,$this->p);
           

        }else{
            $result = db('red_packet_get')->field('FROM_UNIXTIME(add_time,"%Y-%m") as format_time')->where('get_user_id',UID)->group('format_time')->order('add_time desc')->limit(($this->p-1)*1,1)->select();
            if(empty($result)){
                $this->apiReturn(1,'',[]);
            }
            $list = model('common/red_packet')->getRedList("FROM_UNIXTIME(r.add_time,'%Y-%m') = '".$result[0]['format_time']."' and g.get_user_id = ".UID,$this->p);
        }

        $this->apiReturn(1,'列表',[[
            'date' => $result[0]['format_time'],
            'list' => $list
        ]]);
    }
}
